﻿using Microsoft.IdentityModel.Tokens;
using NDLS.WebApi.Model;
using RZWH.WebApi.Model;
using RZWH.WebApi.Model.DBmodels;
using System;
using System.Collections.Generic;
using System.IdentityModel.Tokens.Jwt;
using System.Linq;
using System.Security.Claims;
using System.Text;
using System.Threading.Tasks;

namespace RZWH.WebApi.Services.JWT
{
    public class jwtHelper
    {
        //发放JWT
        public static string IssueJwt(User user)
        {
            // 配置JWT的iss和aud，即发放方和接收方
            string iss = "sjf";
            string aud = "vue";
            // 密钥，用于签名JWT
            string secret = "JD8SD0ASDjsd23j342n547df78ssjffffffffffffff";
            // 创建JWT的payload
            var claims = new List<Claim>
            { 
                // 签发时间
                new Claim(JwtRegisteredClaimNames.Iat, $"{new DateTimeOffset(DateTime.Now).ToUnixTimeSeconds()}"),
                // JWT的唯一标识
                new Claim(JwtRegisteredClaimNames.Jti, user.UserId.ToString()),
                // 生效时间
                new Claim(JwtRegisteredClaimNames.Nbf, $"{new DateTimeOffset(DateTime.Now).ToUnixTimeSeconds()}"),
                // 过期时间
                new Claim(JwtRegisteredClaimNames.Exp, $"{new DateTimeOffset(DateTime.Now.AddSeconds(1200)).ToUnixTimeSeconds()}"),
                // 发放方
                new Claim(JwtRegisteredClaimNames.Iss, iss),
                // 接收方
                new Claim(JwtRegisteredClaimNames.Aud, aud)
            };

            // 添加角色信息到payload
            Claim r1 = new Claim(ClaimTypes.Role, user.RoleId == 0 ? "Admin" : "User");
            claims.Add(r1);

            // 用密钥对JWT进行签名
            var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(secret));
            var creds = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);

            // 创建JWT
            var jwt = new JwtSecurityToken(issuer: iss, claims: claims, signingCredentials: creds);

            // 将JWT转换为字符串格式
            var jwtHandler = new JwtSecurityTokenHandler();
            var encodeJwt = jwtHandler.WriteToken(jwt);

            // 返回JWT字符串
            return encodeJwt;
        }

        public static User DeserializeJwt(string jwtStr)
        {
            // 创建JWT解析器
            var jwtHandler = new JwtSecurityTokenHandler();
            var context = new FluffypawmediaContext();
            User user = new User();

            // 判断JWT字符串是否为空，并且是否能够被解析
            if (!string.IsNullOrEmpty(jwtStr) && jwtHandler.CanReadToken(jwtStr))
            {
                // 解析JWT
                JwtSecurityToken jwtToken = jwtHandler.ReadJwtToken(jwtStr);
                user = context.Users.FirstOrDefault(u => u.UserId == Convert.ToInt64(jwtToken.Id));
            }
            return user;
        }
    }
}

